#pragma once
#include "loggerstream.h"
#include <iostream>
namespace TinyRPC{

LogStream::LogStream(std::ofstream& ofs)
: m_ofstream(ofs)
, m_quit(false){
    m_currentBuffer = new Buffer();
    m_nextBuffer = new Buffer();
    
    m_loggingThread = std::unique_ptr<Thread>(new Thread(std::bind(&LogStream::loggingThreadFunc, this)));
    m_loggingThread->start();
}
LogStream::~LogStream(){
    m_quit = true;
    m_loggingThread->join();
}
void LogStream::log(const std::string& str){
    // 先输出到控制台
    std::cout<<str;
    std::unique_lock<std::mutex> lock(m_mutex);
    m_currentBuffer->append(str);
}

// 单独开一个线程记录日志
// 并且使用双缓冲
// 这里无法自己唤醒
void LogStream::loggingThreadFunc(){
    while (!m_quit)
    {
        //
        //std::cout<<"loggingThreadFunc"<<std::endl;
        sleep(3);
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            Buffer * tmp = m_currentBuffer;
            m_currentBuffer = m_nextBuffer;
            m_nextBuffer = tmp;
        }
        // 将 m_nextBuffer 写入磁盘
        m_ofstream<<m_nextBuffer->read();
    }
    
}

}